package com.song.mall.product.exception;

import com.song.common.exception.BizCodeEnume;
import com.song.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.MessageConstraintException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 宋超
 * HP - the login name of the current user.
 * 2021/8/14 - the current system date.
 * 9:45 - the current system time.
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.song.mall.product.controller")
public class MallExceptionAdvice {


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R HandleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String,String> map = new HashMap<>();
        result.getFieldErrors().forEach((item)->{
            //得到错误提示
            String message = item.getDefaultMessage();
            //得到错误字段
            String field = item.getField();
            map.put(field,message);
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",map);
    }
}
